import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'data/online_pay_info.dart';
import 'data/online_pay_result_info.dart';
import 'data/online_pay_result_state.dart';
import 'data/pay_type.dart';
import 'online_pay_platform_interface.dart';

/// An implementation of [OnlinePayPlatform] that uses method channels.
class OnlinePayMethodChannel extends OnlinePayPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('online_pay');

  @override
  Future<void> initialize({String? wxAppId}) async {
    return methodChannel.invokeMethod('initialize', {'wxAppId': wxAppId});
  }

  /// 发起支付
  /// + `info` 支付信息
  @override
  Future<OnlinePayResultInfo> startPay(OnlinePayInfo? info) async {
    if (info == null) {
      return OnlinePayResultInfo(
          state: OnlinePayResultState.fail, description: '未设置支付参数');
    }
    var result = await methodChannel.invokeMethod('startPay', {
      'type': info.type == PayType.aliPay ? 'ALIPAY' : 'WECHAT_PAY',
      'payInfo': info.payArguments is String
          ? info.payArguments
          : jsonEncode(info.payArguments)
    });
    return OnlinePayResultInfo.fromJson(result);
  }

  @override
  Future<bool> get isWechatInstalled async =>
      (await methodChannel.invokeMethod('isWechatInstalled')) as bool;

  @override
  Future<String?> getPlatformVersion() async {
    return await methodChannel.invokeMethod<String>('getPlatformVersion');
  }
}
